package com.mybatis;

import com.hwf.User;
import com.mysql.cj.protocol.Resultset;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.Proxy;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MapperProxyFactory {
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
    public static <T> T getMapper(Class<T> mapper){
        Object proxyInstance = Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{mapper}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //解析sql  ---->   执行sql   --->  封装结果
                //1.创建数据库连接
                Connection connection = getConnection();
                Select annotation = method.getAnnotation(Select.class);
                String sql = annotation.value();
                System.out.println(sql);

                //参数名：参数信息.
                Map<String,Object> paramValueMapping = new ConcurrentHashMap<>();
                Parameter[] parameters = method.getParameters();
                for (int i = 0; i < parameters.length; i++) {
                    Parameter parameter = parameters[i];
                    String name = parameter.getName();
                    paramValueMapping.put(name,args[i]);
                    //如果有注解就再次put，如果name相同就覆盖以注解为主
                    name = parameter.getAnnotation(Param.class).value();
                    paramValueMapping.put(name,args[i]);
                }

                //2.构造PreparedStatement
                PreparedStatement statement = connection.prepareStatement("select * from user where name = ?");
                statement.setString(1,"hwf");

                //3.执行SQL
                statement.execute();

                //4.封装结果
                List<User> list = new ArrayList<>();
                ResultSet resultSet = statement.getResultSet();
                while (resultSet.next()){
                    User user = new User();
                    user.setId(resultSet.getInt("id"));
                    user.setName(resultSet.getString("name"));
                    user.setAge(resultSet.getInt("age"));
                    list.add(user);
                }

               // System.out.println(list);
                return list;
            }

            private Connection getConnection() throws SQLException {
                return DriverManager.getConnection("jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&serverTimezone=Asia/Shanghai", "root", "root");
            }
        });
        return (T) proxyInstance;
    }
}
